package net.lengwang.iot.middleware.utils;

public class DataEncoder {

    // 将字节数组转换为十六进制字符串
    public static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            hexString.append(String.format("%02X ", b));
        }
        return hexString.toString().trim();
    }

    // 将温度编码为2字节（格式：X = T * 100）
    public static byte[] encodeTemperature(double temperature) {
        int encodedValue = (int) (temperature * 100);
        return intToBytes(encodedValue);
    }

    // 将湿度编码为2字节（格式：X = RH * 100）
    public static byte[] encodeHumidity(double humidity) {
        int encodedValue = (int) (humidity * 100);
        return intToBytes(encodedValue);
    }

    // 将2字节的整数编码为字节数组
    public static byte[] intToBytes(int value) {
        byte[] result = new byte[2];
        result[0] = (byte) ((value >> 8) & 0xFF); // 高字节
        result[1] = (byte) (value & 0xFF); // 低字节
        return result;
    }

    // 将设备ID编码为4字节（假设设备ID是一个整数）
    public static byte[] encodeDeviceId(int deviceId) {
        return new byte[] {
                (byte) ((deviceId >> 24) & 0xFF),
                (byte) ((deviceId >> 16) & 0xFF),
                (byte) ((deviceId >> 8) & 0xFF),
                (byte) (deviceId & 0xFF)
        };
    }

    // BCD码编码，将日期时间转换为6字节的BCD码（格式：yyMMddHHmmss）
    public static byte[] encodeBCDTime(int year, int month, int day, int hour, int minute, int second) {
        byte[] bcdTime = new byte[6];
        bcdTime[0] = intToBcd(year - 2000); // 年份转换成两位BCD码
        bcdTime[1] = intToBcd(month);
        bcdTime[2] = intToBcd(day);
        bcdTime[3] = intToBcd(hour);
        bcdTime[4] = intToBcd(minute);
        bcdTime[5] = intToBcd(second);
        return bcdTime;
    }

    // 将整数转换为BCD码
    private static byte intToBcd(int value) {
        if (value < 0 || value > 99) {
            throw new IllegalArgumentException("数值超出BCD码表示范围");
        }
        int high = value / 10;
        int low = value % 10;
        return (byte) ((high << 4) | low);
    }
}
